<template>
	<view class="page_box">
		<!-- 表单 -->
		<up-form class="mb--20rpx" labelPosition="left" labelWidth="240rpx" :model="formData" :rules="rules"
			ref="upForm">
			<!-- 标题 -->
			<view class="title_box">
				<view class="title_block">
				</view>
				<view class="title_content">
					营业执照信息
				</view>
			</view>
			<up-form-item label="公司名称" prop="corporateName" borderBottom class="form_style">
				<up-input v-model="formData.corporateName" border="none" placeholder="请输入"></up-input>
			</up-form-item>
			<up-form-item label="统一社会信用代码" prop="unifiedSocialCreditCode" borderBottom class="form_style">
				<up-input v-model="formData.unifiedSocialCreditCode" maxlength="18" border="none" placeholder="请输入"></up-input>
			</up-form-item>
			<up-form-item label="法人姓名" prop="legalPersonName" borderBottom class="form_style">
				<up-input v-model="formData.legalPersonName" border="none" placeholder="请输入"></up-input>
			</up-form-item>
			<!-- 标题 -->
			<view class="title_box">
				<view class="title_block">
				</view>
				<view class="title_content">
					申请信息
				</view>
			</view>
			<up-form-item label="申请金额(元)" prop="applicationsAmount" borderBottom class="form_style">
				<up-input v-model="formData.applicationsAmount" @change="handleChange" maxlength="10"  border="none" placeholder="请输入"></up-input>
			</up-form-item>
			<up-form-item label="申请期限"  @click="handleMode('popup_term')" prop="applicationDeadline" borderBottom class="form_style">
				<up-input  v-model="formData.applicationDeadline" disabled border="none" placeholder="请选择"></up-input>
				<template #right>
					<up-icon
						name="arrow-right"
					></up-icon>
				</template>
			</up-form-item>
			<up-form-item label="还款方式" @click="handleMode('popup_mode')" prop="repaymentMethod" borderBottom class="form_style">
				<up-input v-model="formData.repaymentMethod" disabled border="none" placeholder="请输入"></up-input>
				<template #right>
					<up-icon
						name="arrow-right"
					></up-icon>
				</template>
			</up-form-item>
			<up-form-item label="房查流水号" prop="houseNumber" borderBottom class="form_style">
				<up-input v-model="formData.houseNumber" type="number" maxlength="8" border="none" placeholder="请输入"></up-input>
			</up-form-item>
			<up-form-item label="房查手机" prop="housePhone" borderBottom class="form_style">
				<up-input v-model="formData.housePhone" type="number" maxlength="11" border="none" placeholder="请输入"></up-input>
			</up-form-item>
			<up-form-item label="客户经理工号" prop="customerManagerJobNumber" borderBottom class="form_style">
				<up-input v-model="formData.customerManagerJobNumber" type="number" maxlength="10" border="none" placeholder="请输入"></up-input>
			</up-form-item>
		</up-form>
		<!-- 标题 -->
		<view class="title_box">
			<view class="title_block">
			</view>
			<view class="title_content">
				影像采集
			</view>
		</view>
		<view class="file_box">
			<div class="image_box" v-for="(item,index) in formData.fileList" :key="item.url">
				<image :src="item.url" mode="aspectFill" class="image_lists" :class="[item.width/item.height<1?'rotate':'']">
				</image>
				<view class="image_icon" @click="deletePic(index)">
					<up-icon name="close-circle"></up-icon>
				</view>
			</div>
			<up-upload v-if="formData.fileList.length<2" :fileList="fileList" @afterRead="afterRead" multiple
				:maxCount="1">
				<view class="upload_btn">
					<up-icon name="plus" size="28"></up-icon>
					<view class="upload_btn--title">
						身份证正反面
					</view>
				</view>
			</up-upload>
		</view>
		<view class="footer">
			<!-- 以下形式在微信小程序会无效，APP和H5有效  -->
			<view class="custom-style" @click="handleSubmit">提交</view>
		</view>
		<!-- 申请期限弹出框 -->
		<uni-popup ref="popup_term" :mask-click="true" background-color="#fff">
			<view class="term">
				<view class="term-list" @click="setMode(item,'popup_term','applicationDeadline')" v-for="(item,index) in termList" :key="index">
					{{item}}
				</view>
			</view>
		</uni-popup>
		<!-- 还款方式 -->
		<uni-popup ref="popup_mode" :mask-click="true" background-color="#fff">
			<view class="term">
				<view class="term-list" @click="setMode(item,'popup_mode','repaymentMethod')" v-for="(item,index) in modeList" :key="index">
					{{item}}
				</view>
			</view>
		</uni-popup>
		
	</view>
	<!-- 画布 图片方向旋转 -->
	<view style='position: fixed;top: 99rpx;'>
		<canvas :style="{'width':canvasWidth,'height': canvasHeight}" canvas-id="firstCanvas"></canvas>
	</view>
</template>

<script>
	import EXIF from 'exif-js'
	export default {
		props:{
			dataList:{
				type:Object,
				default:{}
			}
		},
		data() {
			return {
				formData: {
					fileList: [],
					corporateName:'',
					unifiedSocialCreditCode:'',
					legalPersonName:'',
					applicationsAmount:'',
					applicationDeadline:'',
					repaymentMethod:'',
					houseNumber:'',
					housePhone:'',
					customerManagerJobNumber:''
				},
				fileList:[],
				options: [{
						label: '选择1',
						value: 1,
					},
					{
						label: '选择2',
						value: 2,
					},
					{
						label: '选择3',
						value: 3,
					}
				],
				termList:[3,6,9,12],
				modeList:['等额本金','等额本息','到期一次性还本付息','按频率付息，到期一次还本'],
				imageSrc:'',
				canvasWidth: '',
				canvasHeight: '',
				isRow:false,
			}
		},
		onLoad() {
		},
	
		methods: {
			deletePic(index) {
				this.formData.fileList = this.formData.fileList.filter((item, itemindex) => itemindex != index)
			},
			afterRead(file, lists, name) {
				// console.log('file',file)
				this.imageSrc = file.file[0].url;
				
				// 验证是否是身份证
				uni.uploadFile({
					url: 'http://116.228.78.26:52800/mobile-bank/face/checkIdCardImg',
					name: 'file',
					filePath: file.file[0].url,
					success: (idCardRes) => {
						// this.getImageOrientation()
						
						console.log('idCardRes',idCardRes)
						let result = JSON.parse(idCardRes.data)
						if ( result.data == "身份证头像面" || result.data == "身份证国徽面") {
							this.formData.fileList = [
								...this.formData.fileList,
								{
									url: file.file[0].url,
									name:result.data
								}
							]
							// this.wake(this.imageSrc, (callback) => {
							// 	console.log(callback, 'callback');
							// 	let img = callback
							// 	// that.srcServe = img;
							// })
							console.log('this.formData.fileList',this.formData.fileList)
						}
						else {
							console.log(result)
							uni.showToast({
								// title: type === 'backImg'?'身份证国徽面不正确':'身份证头像面不正确',
								title:'身份证不正确',
								duration: 2000,
								icon: 'none'
							});
						}
				
					},
				})
				
			},
			// 获取图片方向
			getImageOrientation(){
				// 读取照片的EXIF信息
				    uni.getImageInfo({
				      src: this.imageSrc,
				      success: (imageInfoRes) => {
						  console.log('imageInfoRes',imageInfoRes)
				        // 获取照片的方向信息
				        // const orientation = imageInfoRes.orientation;
						const orientation = this.getOrientationFromExif(imageInfoRes)
				        
				        // 根据orientation的值判断照片的方向
				        switch (orientation) {
				          case 1:
				            console.log('照片为正常方向');
				            break;
				          case 6:
				            console.log('需要旋转90度');
				            break;
				          case 8:
				            console.log('需要旋转-90度');
				            break;
				          case 3:
				            console.log('需要旋转180度');
				            break;
				          default:
				            console.log('未知的方向');
				            break;
				        }
				      },
				      fail: (err) => {
				        console.error('读取照片信息失败:', err);
				      }
				    });
			},
			getOrientationFromExif(imageInfo){
					console.log('imageInfo',imageInfo)
					let obj = {src:this.getBase64(this.imageSrc)}
					EXIF.getData(obj,function(){
						const exifData = EXIF.getAllTags(this)
						const orientation = exifData.Orientation;
						console.log("exifData",exifData)
					},function(error) {
					  // 处理错误情况
					  console.error('获取EXIF数据失败:', error);
					})
			},
			getBase64(img){
				// 读取文件， base64 格式
				const fs = uni.getFileSystemManager();
				// console.log(fs)
				let base64Str = fs.readFileSync(img, 'base64');
				const imgs = `data:image/png;base64,${base64Str}`;
				// console.log('base64-imageSrc',imgs)
				return imgs
			},
			wake(res, callback) {
				const that = this;
				const times = 1;
				let img = null;
				// console.log('（向右）90度旋转 right');
				// console.log('向左）90度旋转 left');
				const direction = "left";
				uni.getImageInfo({
					src: res,
					success: (ress) => {
						img = ress;
						that.canvasWidth = ress.width / 2 + 'px';
						that.canvasHeight = ress.height / 2 + 'px';
			
						console.log('开始旋转',ress);
						//最小与最大旋转方向，图片旋转4次后回到原方向
						var min_step = 0;
						var max_step = 3;
						if (res == null) return;
			
						//img的高度和宽度不能在img元素隐藏后获取，否则会出错
						var height = img.width / 2;
						var width = img.height / 2;
						
						var step = 3;
						//旋转角度以弧度值为参数
						var degree = (step * 90 * Math.PI) / 180;
						var canvas = uni.createCanvasContext('Canvas',this);
						var ctx = uni.createCanvasContext('firstCanvas',this); /** 创建画布 */
						console.log(degree)
						console.log(step)
						
						console.log('左旋转 90度');
						ctx.width = height;
						ctx.height = width;
						ctx.rotate(degree);
						console.log('width',width,'height',height)
						ctx.drawImage(img.path, -width, 0, width, height);
						console.log('666666666666',img.path)
						this.formData.fileList = this.formData.fileList.map((v)=>{
							if(v.url == img.path){
								v.width = width;
								v.height= height;
							}
							return v;
						})	
						console.log("this.formData.fileList",this.formData.fileList)
						
						console.log('绘制完成11111111')
						ctx.draw(false, () => {
						  // 绘制完成后执行
						  console.log('绘制完成2222222222')
						  setTimeout(() => {
							  uni.canvasToTempFilePath({
								   x: 0,  
									y: 0,  
									width: 200,  
									height: 200, 
								canvas: ctx,
								canvasId: 'firstCanvas',
								success: (res) => {
								  console.log('导出图片成功，临时路径为：', res.tempFilePath);
								  // 可以在这里将图片路径传递给图片组件展示，或使用uni.previewImage等API
								},
								fail: (err) => {
								  console.error('导出图片失败11', err);
								},
								complete: () => {
								  console.log('导出操作完成');
								}
							  });
						  },500)
						});	
						// setTimeout(()=>{
						// 	ctx.draw(() => {
						// 		console.log('绘制完成')
						// 		setTimeout(() => {
						// 			console.log('canvasDraw')
						// 			that.canvasDraw(callback)
						// 		}, 1000);
						// 	});
						// },1500)
					}
				})
			},
			canvasDraw(callback) {
				const that = this
				uni.canvasToTempFilePath({
					canvasId: 'firstCanvas',
					success: (res1) => {
						console.log('res1',res1)
						callback(res1.tempFilePath)
					}
				});
			},
			handleMode(name){
				this.$refs[name].open('bottom')
			},
			setMode(val,name,value){
				this.formData[value] = val;
				this.$refs[name].close();
			},
			handleChange(v){
				console.log('v',v)
				let regex = /^[0-9]+(\.[0-9]+)?$/;
				if(!regex.test(v)){
					setTimeout(()=>{
						this.formData.applicationsAmount = v.replace(/[^0-9.]/g,'');
						this.$forceUpdate()
						console.log('res11',!regex.test(v))
					})
				}
			},
			handleSubmit(){
				const regPhone = /^1[3456789]\d{9}$/;
				// const regCreditCode = /^(([0-9A-Za-z]{15})|([0-9A-Za-z]{18})|([0-9A-Za-z]{20}))$/;
				const regCreditCode = /^[0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}$/;
				const regAddress = /[0-9]{8}/;
				if(this.formData.corporateName == ''){
					uni.showToast({
						title:'请输入公司名称',
						icon: 'none'
					})
					return;
				}
				if(!this.formData.corporateName.includes('有限公司')){
					uni.showToast({
						title:'请输入正确的公司名称',
						icon: 'none'
					})
					return;
				}
				if(this.formData.unifiedSocialCreditCode == ''){
					uni.showToast({
						title:'请输入统一社会信用代码',
						icon: 'none'
					})
					return;
				}
				if(!regCreditCode.test(this.formData.unifiedSocialCreditCode)){
					uni.showToast({
						title:'统一社会信用代码不正确',
						icon: 'none'
					})
					return;
				}
				if(this.formData.legalPersonName == ''){
					uni.showToast({
						title:'请输入法人名称',
						icon: 'none'
					})
					return;
				}
				if(this.formData.applicationsAmount == ''){
					uni.showToast({
						title:'请输入申请金额',
						icon: 'none'
					})
					return;
				}
				if(this.formData.applicationDeadline == ''){
					uni.showToast({
						title:'请选择申请期限',
						icon: 'none'
					})
					return;
				}
				if(this.formData.repaymentMethod == ''){
					uni.showToast({
						title:'请选择还款方式',
						icon: 'none'
					})
					return;
				}
				if(this.formData.houseNumber == ''){
					uni.showToast({
						title:'请输入房查流水号',
						icon: 'none'
					})
					return;
				}
				if(!regAddress.test(this.formData.houseNumber)){
					uni.showToast({
						title:'请输入8位的房查流水号',
						icon: 'none'
					})
					return;
				}
				if(this.formData.housePhone == ''){
					uni.showToast({
						title:'请输入房查手机号',
						icon: 'none'
					})
					return;
				}
				if (!regPhone.test(this.formData.housePhone)) {
					uni.showToast({
						title:'手机号格式不正确',
						icon: 'none'
					})
					return;
				}
				// if(this.formData.customerManagerJobNumber == ''){
				// 	uni.showToast({
				// 		title:'请输入客户经理工号',
				// 		icon: 'none'
				// 	})
				// 	return;
				// }
				if(this.formData.fileList.length < 2){
					uni.showToast({
						title:'请上传身份证信息',
						icon: 'none'
					})
					return;
				}
				uni.setStorageSync('formData',JSON.stringify(this.formData))
				uni.navigateTo({
					url:'/packageA/pages/empower'
				})
			},
		},
		computed: {
			rules() {
				return {
					'formData.name': {
						type: 'string',
						required: true,
						message: '请填写姓名',
						trigger: ['blur', 'change']
					}
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.page_box {

		// background-color: #f0f2f5;
		.mb--20rpx {
			margin-bottom: 20rpx;
			padding:0 20rpx;
		}
		.title_box {
			padding: 35rpx 40rpx;
			background-color: #f9f9f9;
			display: flex;
			align-items: center;

			.title_block {
				width: 6rpx;
				height: 18rpx;
				background: linear-gradient(0deg, #FE726F, #F44944);
			}

			.title_content {
				margin-left: 8px;
				font-family: PingFang SC;
				font-weight: bold;
				font-size: 32rpx;
				color: #333333;
			}
		}
		
		.form_style {
			background-color: #ffffff;
			padding: 30rpx 50rpx;
		}

		.file_box {
			padding: 50rpx;
			display:flex;
			.image_box {
				position: relative;
				margin-right: 22rpx;
				margin-bottom: 22rpx;
				width: 324rpx;
				height: 206rpx;

				.image_lists {
					width: 324rpx;
					height: 206rpx;
					box-shadow: 0rpx 2rpx 0rpx 0rpx rgba(24, 24, 24, 0.21);

				}
				.image_lists.rotate{
					transform: rotate(-90deg);
				}

				.image_icon {
					position: absolute;
					top: -8rpx;
					right: -8rpx;
				}
			}

			.upload_btn {
				width: 202rpx;
				height: 202rpx;
				background: #FAFAFA;
				border-radius: 10rpx;
				border: 2px solid #E8E8E8;
				display: flex;
				justify-content: center;
				align-items: center;
				flex-direction: column;

				.upload_btn--title {
					font-family: PingFang SC;
					font-weight: bold;
					font-size: 20rpx;
					color: #999999;
				}
			}
		}

		.footer {
			padding: 36rpx 54rpx;
			background-color: #f1f1f1;

			.custom-style {
				text-align: center;
				line-height: 88rpx;
				height: 88rpx;
				background: linear-gradient(0deg, #FE726F, #F44944);
				box-shadow: 0rpx 7rpx 27rpx 0rpx rgba(243, 74, 70, 0.3);
				border-radius: 44rpx;
				font-family: PingFang SC;
				font-weight: bold;
				font-size: 30rpx;
				color: #FFFFFF;
			}
		}
	}
	.term{
		padding:30rpx 0;
		&-list{
			display: flex;
			justify-content: center;
			padding:20rpx;
		}
	}
</style>